package json;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.junit.Test;
import pojo.Person;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JsonTest {

    //1.javaBean和json的互转
    @Test
    public void Test1() {
        Person person = new Person(1, "周哥");
        //创建Gson对象实例
        Gson gson = new Gson();
        //将JavaBean对象转换成Json字符串
        String personJsonString = gson.toJson(person);
        System.out.println(personJsonString);
        //fromJson把json字符串转换回java对象
        Person person1 = gson.fromJson(personJsonString, Person.class);
        System.out.println(person1);
    }

    //2.list和json的互转
    @Test
    public void Test2() {
        List<Person> personList = new ArrayList<>();
        personList.add(new Person(1, "大神"));
        personList.add(new Person(2, "大佬"));
        //创建Gson对象实例
        Gson gson = new Gson();
        //将list集合转换为json字符串
        String personListJsonString = gson.toJson(personList);
        System.out.println(personListJsonString);
        //将json字符串转换回list集合
        List<Person> list = gson.fromJson(personListJsonString, new PersonListType().getType());
        System.out.println(list);
    }

    //3.map和json的互转
    @Test
    public void Test3() {
        Map<Integer, Person> personMap = new HashMap<>();
        personMap.put(1, new Person(1, "大神"));
        personMap.put(2, new Person(2, "大佬"));
        //创建Gson对象实例
        Gson gson = new Gson();
        //将map集合转换成json字符串
        String personMapJsonString = gson.toJson(personMap);
        System.out.println(personMapJsonString);
        //将json字符串转换回map集合
        //Map<Integer, Person> personMap2 = gson.fromJson(personMapJsonString, new PersonMapType().getType());
        //使用匿名内部类的方法，省去创建一个新的类的过程
        Map<Integer, Person> personMap2 = gson.fromJson(personMapJsonString,
                new TypeToken<HashMap<Integer, Person>>() {}.getType());
        System.out.println(personMap2);
    }
}
